{% extends 'index.html' %}
{% block ace-content %}
<!-- bootstrap-notify -->   
<link href="/static/dist/css/bootstrap-multiselect.css" rel="stylesheet">
<script src="/static/dist/js/bootstrap-multiselect.js"></script>
<script type="text/javascript" src="/static/dist/js/bootstrap-notify.js"></script>
<style type="text/css"> 
  .dropdown-menu {
		max-height: 500px;
		overflow-y: auto;
		overflow-x: hidden;
	} 
</style>		  
{% endblock %}
{% block page-content %}
<div id="page-wrapper">
    <div class="row">
         <div class="col-lg-12">
              <h1 class="page-header"><i class="fa fa-gears"></i><code>Ansible</code>模块管理</h1>
         </div>
                <!-- /.col-lg-12 -->
    </div>
	<div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
 						<i class="fa    fa-gears"></i>模块执行
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-lg-4">
                                <legend><i class="fa  fa-paper-plane"></i> Ansible服务器</legend>
                                    <form role="form" id="ansibleModelRun" class="main form-horizontal" >{% csrf_token %}
										<fieldset>
											<div class="form-group" >			 		             
													<label class="col-sm-2 control-label">动态主机</label>	
													<div class="col-sm-6">
														<select class="form-control" name="server_model" id="server_model" onchange="javascript:oBtAnsibleServerl();">
															<option value="" name="server_model" selected="selected">选择一个类型</option>
															<option value="service" name="server_model">产品线类型</option>		
															<option value="inventory" name="server_model">动态主机组</option>													
															<option value="group" name="server_model">使用部门</option>	
															<option value="custom" name="server_model">自定义</option> 	
														</select>		
													</div>	
											</div>	
											<div id='project_server'  style="display:none;">
												<div class="form-group">
													 <label class="col-sm-2 control-label" >所属产品线</label>
													 <div class="col-sm-6">
			                                            <select class="form-control" name="ansible_project"  id="ansible_project" onchange="javascript:oBtProjectSelect();" required>
			                                            	<option name="project" value="" selected="selected">请选择一个产品线</option>
			                                            	{% for ds in projectList %}
			                                            		<option name="project" value="{{ds.id}}">{{ds.project_name}}</option>
			                                            	{% endfor %}
			                                            </select>
													 </div>
												</div>										
												<div class="form-group">
													 <label class="col-sm-2 control-label" >业务类型</label>
													 <div class="col-sm-6">
			                                            <select class="form-control" name="ansible_service"  id="ansible_service" onchange="javascript:oBtServiceSelect('service','ansible_service');" required>
															<option name="ansible_service" value="" selected="selected">请选择一个应用类型</option>
			                                            </select>
													 </div>
												</div>	
											</div>		
	                                        <div id="inventory_server" class="form-group" style="display:none;">
	                                            <label class="col-sm-2 control-label" >动态主机组<i class="fa fa-info-circle" data-toggle="tooltip"  title="根据动态资产添加选择服务器"></i></label>
	                                            <div class="col-sm-6">
			                                       <select class="form-control" name="ansible_inventory" id="ansible_inventory" onchange="javascript:oBtInventorySelect(this);">
			                                       		<option name="ansible_inventory" value="">选择一个业务类型</option>
			                                           	{% for ds in inventoryList %}
			                                            	<option name="ansible_inventory" value="{{ds.id}}">{{ds.name}}</option>
			                                           {% endfor %}
			                                      </select>
			                                    </div>
	                                        </div> 																				
											<div id="group_server" class="form-group" style="display:none;">
												 <label class="col-sm-2 control-label" >使用部门</label>
												 <div class="col-sm-6">
		                                            <select class="form-control" name="ansible_group"  id="ansible_group" onchange="javascript:oBtServiceSelect('group','ansible_group');" required>
		                                            	<option name="ansible_group" value="" selected="selected">请选择使用组</option>
		                                            	{% for ds in groupList %}
		                                            		<option name="group" value="{{ds.id}}">{{ds.name}}</option>
		                                            	{% endfor %}
		                                            </select>
												 </div>
											</div>																																				
											<div id="custom_server" class="form-group" style="display:none;">
												 <label class="col-sm-2 control-label" >服务器选择</label>
												 <div class="col-sm-6">
		                                            <select multiple name="ansible_server"  id="ansible_server" required>
		                                            	{% for ds in serverList %}
		                                            		<option name="server" value="{{ds.id}}">{{ds.ip}} | {{ds.project}} | {{ds.service}}</option>
		                                            	{% endfor %}
		                                            </select>
												 </div>
											</div>
		                                    <input  type="hidden"   class="form-control"  name="model" value="model">
		                                    <input  type="hidden"   class="form-control" id="ans_uuid" name="ans_uuid" value="{{ans_uuid}}">											
											<div class="form-group" >			 		             
													<label class="col-sm-2 control-label">模块类型</label>	
													<div class="col-sm-6">
														<select class="form-control" name="ansible_model" id="ansible_model" onchange="javascript:oBtAnsibleModel();">
															<option value="ping" name="ansible_model">ping</option>	
															<option value="raw" name="ansible_model">shell</option> 	
															<option value="yum" name="ansible_model">yum</option> 	
															<option value="copy" name="ansible_model">copy</option> 	
															<option value="service" name="ansible_model">service</option>
															<option value="file" name="ansible_model">file</option>	
															<option value="user" name="ansible_model">user</option>	
															<option value="synchronize" name="ansible_model">sync</option>
															<option value="cron" name="ansible_model">cron</option> 	
															<option value="get_url" name="ansible_model">wget</option>
															<option value="custom" name="ansible_model">自定义</option>
														</select>		
													</div>	
											</div>			
											<div id="custom_model" class="form-group" style="display:none;">
												 <label class="col-sm-2 control-label">自定义模块</label>
												 <div class="col-sm-6">											
													<input id="custom_model" type="text"   class="form-control" placeholder="输入模块" name="custom_model" value="">
												</div>
											</div> 											
											</fieldset>																																																					
											<div class="form-group">
												 <label class="col-sm-2 control-label">模块参数</label>
												 <div class="col-sm-6">											
													<input id="ansible_args" type="text"   class="form-control" placeholder="输入模块参数" name="ansible_args" value="">
												</div>
											</div> 	
											<div class="form-group">
												 <label class="col-sm-2 control-label">Debug</label>
												 <div class="col-sm-6">										
														<select class="form-control" name="ansible_debug">
															<option value="off" name="ansible_model">关闭</option>	
															<option value="on" name="ansible_model">开启</option> 	
														</select>
												</div>
											</div> 																					
											</fieldset>
											<legend></legend>
											<div class="form-group">
												<label class="col-sm-3 control-label"></label>
												<button type="button"  onclick="repealFromVaule(this)" class="btn btn-default" >撤销</button>
												{% if perms.OpsManage.can_exec_ansible_model %}
										 			<button type="button"  class="btn btn-default"  id="run_ansible_model" onclick="runAnsibleModel(this)">执行</button>
										 		{% else %}
										 			<button type="button"  class="btn btn-default"  disabled>执行</button>
										 		{% endif %}
									 		</div>									 		
										</form>                                        
                                </div>
                                <!-- /.col-lg-8 (nested) -->
                                <div class="col-lg-8">
                                    <legend><i class="fa  fa-paper-plane-o"></i> 执行结果</legend>
									<pre class="html">
				                        <div id="result">
				                        </div>
				                    </pre>                                      
                                <!-- /.col-lg-6 (nested) -->
                            </div>
                            <!-- /.row (nested) -->
                        </div>
                        <!-- /.panel-body -->
                    </div>
                    <!-- /.panel -->
                </div>
                <!-- /.col-lg-12 -->
            </div>
</div>

<div style="visibility:hidden"><a id="scrollToTop"></a></div>
<script type="text/javascript">


	
$(document).ready(function() {
    $('#ansible_server').multiselect({
        enableClickableOptGroups: true,
        enableCollapsibleOptGroups: true,
        includeSelectAllOption: true,
       	enableFiltering: true, 
    });
});

function oBtInventorySelect(obj){
	   var obj = document.getElementById("ansible_inventory"); 
	   var index = obj.selectedIndex;
	   var sId = obj.options[index].value; 
	   if ( sId  > 0){	 
			$.ajax({
				dataType: "JSON",
				url: "/api/inventory/" + sId +"/", //请求地址
				type:"GET",  //提交类似
				success:function(response){
					if ( JSON.stringify(response["data"]) != '{}'){
						$.notify({
							title: "<strong>发现资产:</strong>",
							message:  "<pre>" + JSON.stringify(response["data"],null,4) + "</pre>",
						},
						{
							type: 'success',
							timer: 3000,
							delay: 30000
						});	
					}
					else {
						$.notify({
							title: "<strong>Ops：</strong>",
							message: "该条件下未发现资产~"
						},
						{
							type: 'danger'
						});
					}
				
						
				},
			});	
	   }
}	

function oBtAnsibleServerl(){
	   var obj = document.getElementById("server_model"); 
	   var index = obj.selectedIndex;
	   var value = obj.options[index].value; 
	   if (value=="group"){
		   document.getElementById("group_server").style.display = "";
		   document.getElementById("custom_server").style.display = "none";
		   document.getElementById("project_server").style.display = "none";
		   document.getElementById("inventory_server").style.display = "none";
	   }
	   else if (value=="custom"){
		   document.getElementById("group_server").style.display = "none";
		   document.getElementById("custom_server").style.display = "";
		   document.getElementById("project_server").style.display = "none";
		   document.getElementById("inventory_server").style.display = "none";
	   }
	   else if (value=="service"){
		   document.getElementById("group_server").style.display = "none";
		   document.getElementById("custom_server").style.display = "none";
		   document.getElementById("project_server").style.display = "";
		   document.getElementById("inventory_server").style.display = "none";
	   }	
	   else if (value=="inventory"){
		   document.getElementById("group_server").style.display = "none";
		   document.getElementById("custom_server").style.display = "none";
		   document.getElementById("project_server").style.display = "none";
		   document.getElementById("inventory_server").style.display = "";
	   }		   
	   else {
		   document.getElementById("group_server").style.display = "none";
		   document.getElementById("custom_server").style.display = "none"; 
		   document.getElementById("project_server").style.display = "none";
		   document.getElementById("inventory_server").style.display = "none";
	   }	
}

function oBtProjectSelect(){
	   $('#ansible_service').removeAttr("disabled");
	   var obj = document.getElementById("ansible_project"); 
	   var index = obj.selectedIndex;
	   var projectId = obj.options[index].value; 
	   if ( projectId > 0){	 
			$.ajax({
				dataType: "JSON",
				url:'/api/project/'+ projectId + '/', //请求地址
				type:"GET",  //提交类似
				success:function(response){
					var binlogHtml = '<select class="form-control" name="ansible_service" id="ansible_service" onchange="javascript:oBtServiceSelect();" required><option selected="selected" name="ansible_service" value="">请选择业务类型</option>'
					var selectHtml = '';
					for (var i=0; i <response["service_assets"].length; i++){
						 selectHtml += '<option name="ansible_service" value="'+ response["service_assets"][i]["id"] +'">' + response["service_assets"][i]["service_name"] + '</option>' 
					};                        
					binlogHtml =  binlogHtml + selectHtml + '</select>';
					document.getElementById("ansible_service").innerHTML= binlogHtml;	
						
				},
			});	
	   }
	   else{
		   $('#ansible_service').attr("disabled",true);
	   }

}

function oBtServiceSelect(model,ids){
	   var obj = document.getElementById(ids); 
	   var index = obj.selectedIndex;
	   var sId = obj.options[index].value; 
	   if ( sId  > 0){	 
			$.ajax({
				dataType: "JSON",
				url:'/assets_server/', //请求地址
				type:"POST",  //提交类似
				data:{
					"query":model,
					"id":sId
				},
				success:function(response){
					var sHtml = '';
					for (var i=0; i <response["data"].length; i++){
						sHtml += '<br>' + response["data"][i]["ip"] + " | " + response["data"][i]["project"] + " | " + response["data"][i]["service"]
					};  
					if ( sHtml.length > 0){
						$.notify({
							title: "<strong>发现主机:</strong>",
							message: sHtml
						},
						{
							type: 'info'
						});	
						$('#run_ansible_model').removeAttr("disabled");
					}
					else {
						$.notify({
							title: "<strong>Ops：</strong>",
							message: "该条件下未发现主机资源~"
						},
						{
							type: 'danger'
						});
						$('#run_ansible_model').attr("disabled",true);
					}
				
						
				},
			});	
	   }
	   else{
		   $('#server option:selected').empty();
		   $('#server').attr("disabled",true);
	   }

}

function oBtAnsibleModel() {
	   var obj = document.getElementById("ansible_model"); 
	   var index = obj.selectedIndex;
	   var value = obj.options[index].value; 
	   if (value=="raw"){
		   document.getElementById("ansible_args").value="uptime";	
		   document.getElementById("custom_model").style.display = "none";
	   }
	   else if (value=="yum"){
		   document.getElementById("ansible_args").value="name=httpd state=present";
		   document.getElementById("custom_model").style.display = "none";
	   }
	   else if (value=="service"){
		   document.getElementById("ansible_args").value="name=httpd state=restarted enabled=yes";
		   document.getElementById("custom_model").style.display = "none";
	   }
	   else if (value=="cron"){
		   document.getElementById("ansible_args").value='name="sync time" minute=*/3 hour=* day=* month=* weekday=* job="/usr/sbin/ntpdate window.time.com"';
		   document.getElementById("custom_model").style.display = "none";
	   }	
	   else if (value=="file"){
		   document.getElementById("ansible_args").value='src=/root/test.txt dest=/tmp/test.txt owner=root group=root mode=700 state=touch';
		   document.getElementById("custom_model").style.display = "none";
	   }	
	   else if (value=="copy"){
		   document.getElementById("ansible_args").value='src=/root/test.txt dest=/tmp/test.txt';	
		   document.getElementById("custom_model").style.display = "none";
	   }	
	   else if (value=="user"){
		   document.getElementById("ansible_args").value="name=welliam password='$6yshUMNL8dhY'";	
		   document.getElementById("custom_model").style.display = "none";
	   }	
	   else if (value=="synchronize"){
		   document.getElementById("ansible_args").value='src=/root/a dest=/tmp/ compress=yes rsync_opts="--exclude=.git --exclude=static/image"';	
		   document.getElementById("custom_model").style.display = "none";
	   }		   
	   else if (value=="get_url"){
		   document.getElementById("ansible_args").value="url=http://url/test.tar.gz dest=/tmp";
		   document.getElementById("custom_model").style.display = "none"; 
	   }		   
	   else if(value=="custom"){
		   document.getElementById("custom_model").style.display = "";  
		   document.getElementById("ansible_args").value="";
	   }
	   else if(value=="ping"){
		   document.getElementById("custom_model").style.display = "none";  
		   document.getElementById("ansible_args").value="";
	   }	   
	   else {
		   document.getElementById("ansible_args").value="";	 
	   }
}
	
		
{% if perms.OpsManage.can_exec_ansible_model %}
	function runAnsibleModel(obj) {
		var btnObj = $(obj);
		btnObj.attr('disabled',true);
		var form = document.getElementById('ansibleModelRun');
		var post_data = {};
		for (var i = 1; i < form.length; ++i) {
			var name = form[i].name;
			var value = form[i].value;
			var project = name.indexOf("ansible_model");
			if ( project==0 && value.length==0 && name!="ansible_args"){
				window.wxc.xcConfirm("请注意必填项不能为空~", window.wxc.xcConfirm.typeEnum.error);
				btnObj.removeAttr('disabled');
				return false;
			}
		};
		$("#result").html("服务器正在处理，请稍等。。。");
		/* 轮训获取结果 开始  */
	   var interval = setInterval(function(){  
	        $.ajax({  
	            url : '/apps/run/',  
	            type : 'post', 
	            data:$('#ansibleModelRun').serialize(),
	            success : function(result){
	            	if (result["msg"] !== null ){
	            		$("#result").append("<p>"+result["msg"]+"</p>"); 
	            		document.getElementById("scrollToTop").scrollIntoView(); 
	            		if (result["msg"].indexOf("[Done]") == 0){
	            			clearInterval(interval);
	            			window.wxc.xcConfirm("Ansible执行完成", window.wxc.xcConfirm.typeEnum.success);
	            			btnObj.removeAttr('disabled');
	            		}
	            	}
	            },
		    	error:function(response){
		    		btnObj.removeAttr('disabled');
		    		clearInterval(interval);
		    	}	            
	        });  
	    },1000); 

// 	    /* 轮训获取结果结束  */
		$.ajax({
			url:'/apps/model/', //请求地址
			type:"POST",  //提交类似
			data:$('#ansibleModelRun').serialize(),  //提交参数
			success:function(response){
				btnObj.removeAttr('disabled');
				if (response["code"] == "500"){
					clearInterval(interval);
					btnObj.removeAttr('disabled');
					window.wxc.xcConfirm(response["msg"], window.wxc.xcConfirm.typeEnum.error);
				}
				
			},
	    	error:function(response){
	    		btnObj.removeAttr('disabled');
	    		window.wxc.xcConfirm("运行失败", window.wxc.xcConfirm.typeEnum.error);
	    		clearInterval(interval);
	    	}
		})	
	}	
{% endif %}

{% if errorInfo %}
	window.wxc.xcConfirm("{{errorInfo}}", window.wxc.xcConfirm.typeEnum.error);
{% endif %}
</script>

{% endblock %}